﻿//// 
////  --- our app behavior logic ---
////
//alert('do you know me');
//var contactService = (function () {

//    function initiate() {
//        alert('junk');
//        console.log('of course');
//        return true;
//    }

//    when("#tab-container", function () {
//        $("#contactsContainer").html("loading contacts...");

//        }

//    );
//});


/*jslint */
/*global openDatabase: true, $: true */
"use strict";
//

var contactsService = (function () {

    function errorHandler(transaction, error) {
        console.log('Oops. Error was ' + error.message + ' (Code ' + error.code + ')');
        return true;
    }

    function onSuccess_SearchContacts(contacts) {

     
        for (var i = 0; i < contacts.length; i++) {
            //alert(contacts[i].displayName);

            // display phone numbers
            /*if (contacts[i].emails) {
                for (var j = 0; j < contacts[i].emails.length; j++) {
                    alert("Type: " + contacts[i].emails[j].type + "\n" +
                            "Value: " + contacts[i].emails[j].value + "\n" +
                            "Preferred: " + contacts[i].emails[j].pref);
                }
            }

            if (contacts[i].phoneNumbers) {
                for (var j = 0; j < contacts[i].phoneNumbers.length; j++) {
                    alert("Type: " + contacts[i].phoneNumbers[j].type + "\n" +
                            "Value: " + contacts[i].phoneNumbers[j].value + "\n" +
                            "Preferred: " + contacts[i].phoneNumbers[j].pref);
                }
            }
			*/
            var itemToAdd = '<li>'
								+ '<a class="cdetails" href="' + i + '" style="margin-top: -8px">'
										+ '<img src="images/live/face1.png" alt="" />'
										+ '<span class="contactName">'
											+ '<strong>' + contacts[i].displayName + '<span></span></strong>'
											+ '<i>xxx days</i>'
										+ '</span>'
										+ '<span class="status_away"> </span>'
										+ '<span class="clear"></span>'
								+ '</a>'
							+ '</li>';

            $("#contactList").append(itemToAdd);
        }

    };

    // onError: Failed to get the contacts
    //
    function onError_SearchContacts(contactError) {
        alert('onError!');
        $("#contactsContainer").html("ERROR.unable to load contacts...");
    }


    return {



        /* LIST CONTACTS */
        listContacts: function () {
            console.log('listContacts');
           
            // specify contact search criteria
            var options = new ContactFindOptions();
            options.filter = "";          // empty search string returns all contacts
            options.limit = "";
            options.multiple = true;      // return multiple results
            var fields = ["displayName", "name", "emails", "phoneNumbers"];   // return contact.displayName field

            // find contacts
            navigator.contacts.find(fields, onSuccess_SearchContacts, onError_SearchContacts, options);
            return false;
        },




        /* INITIATE */
        //load the initial list
        initiate: function () {

            console.log('initiate');
            
            //show message
            $("#loadingContainer").css("display", "inline");
           
            //get the lists
            this.listContacts();

            //hide message
            $("#loadingContainer").css("display", "none");

        },




        //Create a category entry in the database
        createContact: function (entry) {

            var noPicture = "";


            if (online) {
                db.transaction(
                    function (transaction) {
                        transaction.executeSql(
                             'INSERT OR REPLACE INTO contacts (fullName, url, memberId, location, status, picture, company, position, past, current) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
                          [entry.fullName, entry.url, entry.memberId, entry.location, entry.status, noPicture, entry.company, entry.position, entry.past, entry.current], null, errorHandler
                    );
                    }
            );
                return false;
            }
        },


        //get all child categories of 'path' from database
        getContacts: function (callback) {

            db.transaction(
                function (transaction) {
                    transaction.executeSql(
                        'SELECT * FROM contacts', [],
                        function (transaction, result) {
                            var contacts = [], i, row;
                            for (i = 0; i < result.rows.length; i += 1) {
                                row = result.rows.item(i);
                                contacts.push(row);
                            }
                            callback(contacts);
                        }, errorHandler);
                }
            );
        },


        // Delete table from database
        dropTable: function () {
            db.transaction(
                function (transaction) {
                    transaction.executeSql("DROP TABLE contacts", [], null, errorHandler);
                }
            );
        },


        //isTableExists
        isTableExists: function (tableName, callback) {
            alert('isTableExists - searching for: ' + tableName);
            db.transaction(
                function (transaction) {
                    transaction.executeSql('SELECT * FROM ' + tableName, [], function (tx, resultSet) {
                        if (resultSet.rows.length <= 0) {
                            callback(false, 'no data');
                        } else {
                            callback(true, '');
                        }
                    }, function (transaction, err) {
                        errorHandler(transaction, err)
                        callback(false, err.message);
                    }); //transaction.executeSql
                });
        }//END isTableExists



    };
}());

